package com.lg.rpc.common.protocol.util;

import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtostuffIOUtil;
import com.dyuproject.protostuff.Schema;
import com.dyuproject.protostuff.runtime.RuntimeSchema;
import lombok.extern.slf4j.Slf4j;
import org.objenesis.Objenesis;
import org.objenesis.ObjenesisStd;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Serialization Util（Based on protoBuff）
 *
 * @author by Mr. Li 2020/5/21 22:19
 */
@Slf4j
public class SerializationUtil {
    private static Map<Class<?>, Schema> cachedSchema = new ConcurrentHashMap<>();

    private static Objenesis objenesis = new ObjenesisStd(true);

    public SerializationUtil() {
    }


    @SuppressWarnings("unchecked")
    private static <T> Schema<T> getTSchema(Class<T> clazz) {
        //Schema<T> schema = (Schema<T>) cachedSchema.get(clazz);
        //if (schema == null) {
        //    schema = RuntimeSchema.createFrom(clazz);
        //    if (schema != null) {
        //        cachedSchema.put(clazz, schema);
        //    }
        //}
        //return schema;
        //for thread - safe

        return (Schema<T>) cachedSchema.computeIfAbsent(clazz, RuntimeSchema::createFrom);
    }

    /**
     * 序列化(对象 -> 字节数组)
     *
     * @param obj
     * @param <T>
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> byte[] serialize(T obj) {
        Class<T> cls = (Class<T>) obj.getClass();
        LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);

        try {
            Schema<T> tSchema = getTSchema(cls);

            return ProtostuffIOUtil.toByteArray(obj, tSchema, buffer);
        } catch (Exception e) {
            log.error("Protobuf 序列化失败,e:{}", e.getMessage());
            throw new IllegalStateException("Protobuf 序列化失败");
        } finally {
            buffer.clear();
        }
    }

    /**
     * 反序列化 (字节数组 -> 对象)
     *
     * @param data
     * @param cls
     * @param <T>
     * @return
     */
    public static <T> T deserialize(byte[] data, Class<T> cls) {
        try {
            T message = (T) objenesis.newInstance(cls);
            Schema<T> schema = getTSchema(cls);
            ProtostuffIOUtil.mergeFrom(data, message, schema);
            return message;
        } catch (Exception e) {
            log.error("Protobuf 反序列化失败,e:{}", e.getMessage());
            throw new IllegalStateException("Protobuf 反序列化失败");
        }
    }
}
